package com.mutouren.modules.sso.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mutouren.common.entity.ResultCode;
import com.mutouren.common.entity.SignResultInfo;
import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.mutouren.common.session.UserInfo;
import com.mutouren.common.utils.DigestUtils;
import com.mutouren.common.utils.HttpClientUtils;
import com.mutouren.common.utils.HttpResult;

public class SsoProxy {
	private static final String ssoLogin_suf = "/sso/login.action"; 
	private static final String ssoGetUserInfo_suf = "/sso/getUserInfo.action";

	private static String ssoLoginUrl;
	private static String ssoGetUserInfoUrl;
	
	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());	
	
	public static void init(String contextURL) {
		ssoLoginUrl = contextURL + ssoLogin_suf;
		ssoGetUserInfoUrl = contextURL + ssoGetUserInfo_suf;
	}
	
	public static String getSsoLoginUrl(String appAlias, String redirect_uri, String state) {
		String url = String.format("%s?appAlias=%s&redirect_uri=%s&state=%s", 
				ssoLoginUrl, appAlias, redirect_uri, state);
		return url;
	}
	public static String getSsoGetUserInfoUrl() {
		return ssoGetUserInfoUrl;
	}
	
	public static SignResultInfo<UserInfo> getUserInfo(String appAlias, String appSecret, String ticket) {
		SignResultInfo<UserInfo> result;
		
		HttpClientUtils httpClient = new HttpClientUtils(ssoGetUserInfoUrl, "GET");
		httpClient.addParameter("appAlias", appAlias);		
		httpClient.addParameter("ticket", ticket);
		
		HttpResult httpResult;
		try {
			httpResult = httpClient.execute();

			if(httpResult.isSuccess()) {
				String body = httpResult.getContent("utf-8");
				result = JSON.parseObject(body, new TypeReference<SignResultInfo<UserInfo>>(){});  
				
				// 校验sign
				if ((result.getCode() == ResultCode.SUCCESS.value) && (!checkSign(result, appSecret))) {
					result.setCode(ResultCode.FAIL.value);
					result.setMessage("sign校验失败");
				}				
			} else {
				result = new SignResultInfo<UserInfo>(ResultCode.EXCEPTION.value, "OrgApiProxy.login: request fail");
			}
		} catch(Throwable t) {
			result = new SignResultInfo<UserInfo>(ResultCode.EXCEPTION.value, t.getMessage());
			errorLogger.error("OrgApiProxy.login error", t);
		} finally {
			// log
		}
		
		return result;
	}
	
	private static boolean checkSign(SignResultInfo<UserInfo> result, String appSecret) {		
		//result.setTimestamp(new Date().getTime());
		UserInfo userInfo = result.getInfo();
		
		String sourceSign = String.format("%s%s%s%s%s", 
				userInfo.getUserName(), 
				userInfo.getEmail() == null ? "" : userInfo.getEmail().trim(), 
				userInfo.getMobile() == null ? "" : userInfo.getMobile().trim(),
				result.getTimestamp(), appSecret);
		String sign = DigestUtils.MD5(sourceSign);
		
		return sign.equals(result.getSign());
	}	
}
